//
//  CZStatusListViewModel.swift
//  weiBo
//
//  Created by apple on 16/5/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZStatusListViewModel: NSObject {

    var statusList: [CZStatusViewModel]?
    
    func requestStatus(isPullUp: Bool, complete: (isSuccess: Bool)->()){
        //判断是不是上啦加载
        var maxId: Int64 = 0
        //判断是不是下拉舒心
        var sinId: Int64 = 0
        //上啦加载更多
        if isPullUp {
            maxId = self.statusList?.last?.status?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            
            }
        }else {
            //下拉刷新
            sinId = self.statusList?.first?.status?.id ?? 0
        }
        
        
        CZNetWorkTools.shareTools.requestStatus(CZUserCountViewModel.sharedUserAccount.access_token!, maxId: maxId,sinceId: sinId) { (response, error) -> () in
            if error != nil{
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            
            guard let dic = response as? [String : AnyObject] else{
                print("不是json类型")
                complete(isSuccess: false)

                return
            }
            guard let statusArray = dic["statuses"] as? [[String: AnyObject]] else {
                print("不是数组类型")
                complete(isSuccess: false)

                return
            }
            
            
            var tempArray = [CZStatusViewModel]()
            for value in statusArray{
                let status = CZStatus(dict: value)
                let statusViewModel = CZStatusViewModel(status: status)
                tempArray.append(statusViewModel)
            }
            if self.statusList == nil {
                self.statusList = [CZStatusViewModel]()
            }
            //刷新数据
            if isPullUp {
                //追加数据
                self.statusList = self.statusList! + tempArray
            }else {
                self.statusList = tempArray + self.statusList!
            }
            //通过闭包回调数据
            complete(isSuccess: true)
        }
        
    }

    

    
}
